package com.irdstudio.efp.edoc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.efp.edoc.common.UploadFileConstant;
import com.irdstudio.efp.edoc.service.bo.UpLoadFileVO;
import com.irdstudio.efp.edoc.service.dao.UpLoadFileDao;
import com.irdstudio.efp.edoc.service.domain.UpLoadFile;
import com.irdstudio.efp.edoc.service.facade.UpLoadFileService;
import com.irdstudio.efp.esb.common.constant.nls.NlsProdCdEnum;
import com.irdstudio.efp.loan.service.facade.AccLoanService;
import com.irdstudio.efp.loan.service.vo.AccLoanVO;
import com.irdstudio.efp.nls.service.facade.NlsApplyInfoService;
import com.irdstudio.efp.nls.service.vo.NlsApplyInfoVO;
import com.sunyard.client2.FileNameEnums;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 影像平台上传
 *
 * @author heyingfeng
 * @version 1.0
 * @since 2019年1月4日 下午7:23:02
 */
@Service("upLoadFileService")
public class UpLoadFileServiceImpl implements UpLoadFileService, FrameworkService {

    private static Logger logger = LoggerFactory.getLogger(UpLoadFileServiceImpl.class);

    @Autowired
    private UpLoadFileDao upLoadFileDao;

    @Autowired
    private AccLoanService accLoanService;

    @Autowired
    private NlsApplyInfoService nlsApplyInfoService;

    /**
     * 新增操作
     */
    public int insertUpLoadFile(UpLoadFileVO upLoadFileVo) {
        logger.info("当前新增数据为:" + upLoadFileVo.toString());
        int num = 0;
        try {
            num = upLoadFileDao.insertUpLoadFile(upLoadFileVo);
        } catch (Exception e) {
            logger.error("新增数据发生异常!" + e.getMessage());
            num = -1;
            e.printStackTrace();
        }
        logger.info("当前新增数据条数为:" + num);
        return num;
    }

    /**
     * 查询操作
     */
    @SuppressWarnings("unchecked")
    public List<UpLoadFileVO> queryUploadFile(UpLoadFileVO upLoadFileVo) {
        logger.info("当前查询文件上传影像平台为:" + JSONObject.toJSONString(upLoadFileVo));
        List<UpLoadFileVO> list = null;
        try {
            List<UpLoadFile> upLoadFiles = upLoadFileDao.queryUploadFile(upLoadFileVo);
            logger.info("当前查询文件上传影像平台的结果集数量为:" + upLoadFiles.size());
            list = (List<UpLoadFileVO>) beansCopy(upLoadFiles, UpLoadFileVO.class);
        } catch (Exception e) {
            logger.error("数据转换出现异常!" + e.getMessage());
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 更新操作
     */
    public int updateUpLoadFile(UpLoadFileVO upLoadFileVo) {
        logger.info("当前更新数据为:" + upLoadFileVo.toString());
        int num = 0;
        try {
            num = upLoadFileDao.updateUpLoadFile(upLoadFileVo);
        } catch (Exception e) {
            logger.error("更新数据发生异常!" + e.getMessage());
            num = -1;
            e.printStackTrace();
        }
        logger.info("当前更新数据条数为:" + num);
        return num;
    }

    /**
     * 查询操作
     */
    @Override
    public UpLoadFileVO queryUploadFileByApplySeqAndImageType(UpLoadFileVO upLoadFileVO) {
        logger.info("当前查询文件上传影像平台为:");
        UpLoadFileVO queryUpLoadFileVO = new UpLoadFileVO();
        try {
            UpLoadFile queryUpLoadFile = upLoadFileDao.queryUploadFileByApplySeqAndImageType(upLoadFileVO);
            logger.info("当前查询文件上传影像平台的信息为:" + JSONObject.toJSONString(queryUpLoadFile));
            beanCopy(queryUpLoadFile, queryUpLoadFileVO);
        } catch (Exception e) {
            logger.error("数据转换出现异常!" + e.getMessage());
            e.printStackTrace();
        }
        return queryUpLoadFileVO;
    }
//	@author:liuty
//	@date:2019/10/17
//	涉及产品:税e贷
//	原因:增量投产只投了接口没投实现，编译报错因此注释，不影响当前产品实际业务
//	@Override
//	public List<UpLoadFileVO> queryUploadFileInTypeList(List<String> imageTypeList) {
//
//		List<UpLoadFile> upLoadFiles = this.upLoadFileDao.queryUploadStamFile(imageTypeList);
//
//		List<UpLoadFileVO> upLoadFileVOS =null;
//
//		upLoadFileVOS=	upLoadFiles != null ? beanCopy(upLoadFiles, upLoadFileVOS) : null;
//
//		return upLoadFileVOS;
//
//
//	}
//
//	@Override
//	public UpLoadFileVO queryFirstUpLoadFileByReq(String req,String status) {
//        UpLoadFileVO upLoadFileVO=null;
//        UpLoadFile upLoadFile = this.upLoadFileDao.queryFirstUpLoadFileByReq(req,status);
//        if (upLoadFile!=null) {
//            upLoadFileVO=new UpLoadFileVO();
//            beanCopy(upLoadFile,upLoadFileVO);
//        }
//        return upLoadFileVO;
//
//    }

    /**
     * 接口测试开始
     **/
    public int testUp(UpLoadFileVO vo) {
        logger.info("接口上传测试:");
        int outputVo = 0;
        String urlFile = vo.getFilePath();// 文件夹路径
        String ret = "";
        try {
            ret = UploadFileConstant.uploadFile(vo, urlFile);
            String[] result = ret.split("<<::>>");
            File path = new File(urlFile);
            File[] files = path.listFiles();
            for (int i = 0; i < files.length; i++) {// 循环文件插入表
                UpLoadFileVO upLoadFileVo = new UpLoadFileVO();
                upLoadFileVo.setApplySeq(vo.getApplySeq());
                String dateFile = files[i].getName().substring(files[i].getName().indexOf("_") + 1, files[i].getName().lastIndexOf("."));// 文件属性值
                if ("".equals(dateFile) || dateFile == null) {
                    dateFile = "unkonw";
                }
                upLoadFileVo.setImageType(FileNameEnums.map.get(dateFile));
                upLoadFileVo.setFilePath(urlFile);
                upLoadFileVo.setStartDate(vo.getStartDate());
                upLoadFileVo.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                upLoadFileVo.setLastModifyTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                upLoadFileVo.setCertCode(vo.getCertCode());
                upLoadFileVo.setCusName(vo.getCusName());
                upLoadFileVo.setPrdName(vo.getPrdName());
                // SUCCESS<<::>>20190116-E3BD0CCF-FE36-951F-88F3-38821BF7A50C-1
                // FAIL<<::>>20190116-F453F865-2103-7FC1-A605-1C39AD4799AE-1<<::>>743
                if (result.length > 2) {// 失败
                    upLoadFileVo.setState(result[0]);// 状态
                    upLoadFileVo.setBatch(result[1]);// 返回批次号
                    upLoadFileVo.setStateNum(result[2]);// 失败状态码
                } else {
                    upLoadFileVo.setState(result[0]);// 状态
                    upLoadFileVo.setBatch(result[1]);// 返回批次号
                }
                outputVo += insertUpLoadFile(upLoadFileVo);
            }
        } catch (Exception e) {
            logger.error("接口上传测试!" + e.getMessage());
            e.printStackTrace();
        }
        return outputVo;
    }

    public String testQuery(UpLoadFileVO vo) {
        logger.info("接口查询测试:");
        String contentId = vo.getBatch();
        String startDate = vo.getStartDate();
        String dataFile = vo.getImageType();// 如需要查询单个文件，赋值文件属性
        String ret = "";
        try {
            ret = UploadFileConstant.queryBatchFile(contentId, startDate, dataFile);
        } catch (Exception e) {
            logger.error("接口查询测试!" + e.getMessage());
            e.printStackTrace();
        }
        return ret;
    }

    public int testAdd(UpLoadFileVO vo) {
        logger.info("接口追加测试:");
        int outputVo = 0;
        String contentId = vo.getBatch();
        String startDate = vo.getStartDate();
        String urlFile = vo.getFilePath();// 如需要查询单个文件，赋值文件属性
        String applySeq = "20190215";
        String ret = "";
        try {
            UpLoadFileVO upLoadFileVo = new UpLoadFileVO();
            ret = UploadFileConstant.updateBatchFile(applySeq, contentId, urlFile, startDate);// 追加文件
            File path = new File(urlFile);
            String dateFile = path.getName().substring(path.getName().indexOf("_") + 1, path.getName().lastIndexOf("."));// 文件属性值
            Pattern p = Pattern.compile(".*\\d+.*");
            Matcher m = p.matcher(dateFile);
            if (m.matches()) {// 包含数字，为保单
                dateFile = "unkonw";
            }
            upLoadFileVo.setImageType(FileNameEnums.map.get(dateFile));
            upLoadFileVo.setApplySeq(vo.getApplySeq());
            upLoadFileVo.setBatch(contentId);
            upLoadFileVo.setFilePath(urlFile);
            upLoadFileVo.setStartDate(startDate);
            upLoadFileVo.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            upLoadFileVo.setLastModifyTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            // 成功 返回成功信息success
            // 失败 返回失败信息+异常代码,例如: FAIL<<::>>733
            upLoadFileVo.setAddFileState(ret);
            outputVo += insertUpLoadFile(upLoadFileVo);
        } catch (Exception e) {
            logger.error("接口追加测试!" + e.getMessage());
            e.printStackTrace();
        }
        return outputVo;
    }

    public String testDown(UpLoadFileVO vo, String resultMsg, String index) {
        logger.info("接口下载测试:");
        String contentId = vo.getBatch();
        String startDate = vo.getStartDate();
        String ret = "";
        String urlFile = "";
        String systemType = "test/";
        try {
            ret = UploadFileConstant.queryAndDownload(resultMsg, contentId, startDate, index, systemType, urlFile);// 下载文件，index = 1为下载
        } catch (Exception e) {
            logger.error("接口下载测试!" + e.getMessage());
            e.printStackTrace();
        }
        return ret;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<UpLoadFileVO> qryInfosByApplySeq(UpLoadFileVO upLoadFileVO) {
        logger.debug("分页查询信息的参数信息为:" + upLoadFileVO);
        List<UpLoadFileVO> list = null;
        try {
            UpLoadFile upLoadFile = beanCopy(upLoadFileVO, new UpLoadFile());
            List<UpLoadFile> upLoadFiles = upLoadFileDao.qryInfosByPage(upLoadFile);
            logger.debug("数据信息的结果集数量为:" + upLoadFiles.size());
            pageSet(upLoadFiles, upLoadFile);
            list = (List<UpLoadFileVO>) beansCopy(upLoadFiles, UpLoadFileVO.class);
        } catch (Exception e) {
            logger.error("数据转换出现异常!", e);
        }
        return list;
    }

    @Override
    public int testDelete(UpLoadFileVO upLoadFileVO) {
        logger.debug("当前删除数据条件为:" + JSON.toJSONString(upLoadFileVO));
        int num = 0;
        try {
            UpLoadFile upLoadFile = new UpLoadFile();
            beanCopy(upLoadFileVO, upLoadFile);
            num = upLoadFileDao.deleteByPk(upLoadFile);
        } catch (Exception e) {
            logger.error("删除数据发生异常!", e);
            num = -1;
        }
        logger.debug("根据条件:" + JSON.toJSONString(upLoadFileVO) + "删除的数据条数为" + num);
        return num;
    }

    /**
     * 存量影像信息到上传信息有数据则更新，无则新增 <br>
     * 0.1:weijj:2019年5月7日 下午2:37:18:新增 <br>
     *
     * @author weijj
     * @date 2019年6月4日 下午2:37:18
     * @version 0.1
     * @since 2019年6月4日 下午2:37:18
     */
    @SuppressWarnings("unchecked")
    @Override
    public int insertOrUpdateUpLoadFileList(List<UpLoadFileVO> list) {
        // TODO Auto-generated method stub
        LocalDate today = LocalDate.now();
        String msg1 = "【上传影像信息表】数据同步开始..." + today;
        logger.info(msg1, "message{}");
        List<UpLoadFile> upLoadFileList = new ArrayList<UpLoadFile>();
        int num = 0;
        try {
            upLoadFileList = (List<UpLoadFile>) beansCopy(list, UpLoadFile.class);
            num = upLoadFileDao.insertOrUpdateUpLoadFileList(upLoadFileList);
            String num_msg = "【上传影像信息表】插入或更新数据处理结果:" + num;
            logger.info(num_msg, "message{}");
        } catch (Exception e) {
            String msg2 = "【上传影像信息表】插入或更新数据出现异常:" + e;
            logger.error(msg2, "message{}");
            num = -1;
        }
        return num;
    }

    /**
     * 该查询接口用于查询出适合的记录做展示跳转到影响系统
     *
     * @param prdId      产品编码（必输）
     * @param applySeq   流水号（必输）
     * @param imageTypes 影像类型（选输）
     * @return List<UpLoadFileVO>
     * @throws Exception
     */
    @Override
    public List<UpLoadFileVO> queryForImgSys(String prdId, String applySeq, List<String> imageTypes) throws Exception {
        HashMap params = new HashMap();
        ArrayList<String> applySeqs = new ArrayList<>();
        //如果是马上的产品 那么直接根据流水号查询记录
        if (NlsProdCdEnum.MS.getValue().equals(prdId)) {
            applySeqs.add(applySeq);
        } else {
            applySeqs.add(applySeq);
            AccLoanVO accLoanPkParam = new AccLoanVO();
            accLoanPkParam.setBillNo(applySeq);
            AccLoanVO accLoanVO = Optional.ofNullable(accLoanService.queryByPk(accLoanPkParam)).orElseGet(AccLoanVO::new);
            //获取用信流水号，获取授信流水号
            String nlsApplySeq = accLoanVO.getApplySeq();
            if (StringUtils.isNotEmpty(nlsApplySeq)) {
                NlsApplyInfoVO nlsApplyInfoVOPkParam = new NlsApplyInfoVO();
                nlsApplyInfoVOPkParam.setApplySeq(nlsApplySeq);
                NlsApplyInfoVO nlsApplyInfoVO = Optional.ofNullable(nlsApplyInfoService.queryByPk(nlsApplyInfoVOPkParam)).orElseGet(NlsApplyInfoVO::new);
                applySeqs.add(nlsApplySeq);
                applySeqs.add(nlsApplyInfoVO.getLmtApplySeq());
            }
        }
        params.put("applySeqs", applySeqs);
        params.put("imageTypes", imageTypes);
        return (List<UpLoadFileVO>) beansCopy(this.upLoadFileDao.queryForImgSys(params), UpLoadFileVO.class);
    }

	@Override
	public UpLoadFileVO queryFirstUpLoadFileByReq(String req,String status) {
		UpLoadFileVO upLoadFileVO=null;
		UpLoadFile upLoadFile = this.upLoadFileDao.queryFirstUpLoadFileByReq(req,status);
		if (upLoadFile!=null) {
			upLoadFileVO=new UpLoadFileVO();
			beanCopy(upLoadFile,upLoadFileVO);
		}
		return upLoadFileVO;

	}
}
